<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      :page.sync="page"
      :data="tableData"
      :table-loading="tableLoading"
      :option="tableOption"
      :before-open="beforeOpen"
      @on-load="getList"
      @search-change="searchChange"
      @search-reset="searchReset"
      @row-update="handleUpdate"
      @row-save="handleSave"
    >
      <template
        slot="menu"
        slot-scope="scope"
      >
        <el-button
          v-if="scope.row.status === ADVERTISING_STATUS.NOT_OPEN"
          type="text"
          size="small"
          @click="updateSearchStatus(scope.row, ADVERTISING_IS_DISABLED.ENABLE)"
        >
          启用
        </el-button>
        <el-button
          v-if="[ADVERTISING_STATUS.NOT_STARTED, ADVERTISING_STATUS.UNDERWAY,ADVERTISING_STATUS.FINISHED].includes(scope.row.status)"
          type="text"
          size="small"
          @click="updateSearchStatus(scope.row, ADVERTISING_IS_DISABLED.FORBIDDEN)"
        >
          禁用
        </el-button>
      </template>
      <template #keywordsJsonForm="{type}">
        <div>
          <div v-if="type !== 'view'">请选择关联以下筛选条件</div>
          <div class="flex mb-20">
            <div class="title">品种：</div>
            <el-select
              v-model="breed"
              clearable
              style="width: 300px !important;"
              placeholder="请选择"
            >
              <el-option
                v-for="item in breedList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              >
              </el-option>
            </el-select>
          </div>
          <div class="flex mb-20">
            <div class="title">性别：</div>
            <el-select
              v-model="gender"
              clearable
              style="width: 300px !important;"
              placeholder="请选择"
            >
              <el-option
                v-for="item in genderList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <template v-for="(v, k) in attributeList">
            <div
              :key="k"
              class="flex mb-20"
            >
              <div class="title">{{ v.attributeName }}：</div>
              <el-select
                v-model="v.bindValue"
                clearable
                style="width: 300px !important;"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in v.items"
                  :key="item.attributeCode"
                  :label="item.attributeName"
                  :value="item.attributeCode"
                >
                </el-option>
              </el-select>
            </div>
          </template>
        </div>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {
  fetchList,
  updateSearchStatus,
  addObj,
  putObj,
  getObj,
} from '@/api/operation/hot-term';
import { tableOption } from '@/const/crud/search/hot-terms';
import { mapGetters } from 'vuex';
import crudMixins from '@/mixins/crud';
import { getListByCode, getListByClassifyCode } from '@/api/core/classify';
import { remote } from '@/api/admin/dict';
import {
  ADVERTISING_STATUS,
  ADVERTISING_IS_DISABLED,
  SEARCH_TYPE,
  SEARCHABLE_TYPE,
} from '@/const/type';
export default {
  name: 'advertisingList',
  components: {},
  mixins: [crudMixins],
  data() {
    return {
      form: {},
      tableOption: tableOption(),
      id: null,
      list: [{}],
      breed: '',
      breedList: [],
      attributeList: [],
      // attributeItemList: [],
      ADVERTISING_STATUS,
      ADVERTISING_IS_DISABLED,
      gender: '',
      genderList: [],
    };
  },
  computed: {
    ...mapGetters(['permissions']),
  },
  watch: {
    'form.jumpType'(val) {
      if (val === SEARCH_TYPE.PET_RESULT) {
        this.resetData();
      }
    },
  },
  async mounted() {
    await this.getBreedData();
    await this.getGender();
    await this.getAttributeData();
  },
  methods: {
    // 获取猫的品种list数据
    async getBreedData() {
      try {
        const { data } = await getListByCode('CAT');
        this.breedList = data.data;
      } catch (error) {
        throw new Error(error);
      }
    },
    resetData() {
      this.breed = '';
      this.gender = '';
      this.attributeList.forEach(async (el) => {
        this.$set(el, 'bindValue', '');
      });
    },
    // 获取宠物性别数据
    async getGender() {
      try {
        const { data } = await remote('pet_sex');
        this.genderList = data.data;
      } catch (error) {
        throw new Error(error);
      }
    },
    // 获取属性数据
    async getAttributeData() {
      try {
        const { data } = await getListByClassifyCode('CAT');
        this.attributeList = data.data.filter(
          (el) => el.queryFlag === SEARCHABLE_TYPE.YES
        );
        this.attributeList.forEach(async (el) => {
          this.$set(el, 'bindValue', '');
        });
      } catch (error) {
        throw new Error(error);
      }
    },
    updateSearchStatus(row, disableFlag) {
      const tip =
        disableFlag === ADVERTISING_IS_DISABLED.ENABLE ? '开启' : '禁用';
      this.$confirm(`【是否确认${tip}该搜索词】`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        await updateSearchStatus({
          id: row.id,
          disableFlag,
        });
        this.$message.success(`${tip}成功`);
        this.getList(this.page, true);
      });
    },
    getParams(row, loading) {
      const params = { ...row };
      if (params.jumpType === SEARCH_TYPE.PET_RESULT) {
        // const flag =
        //   this.validatenull(this.breed) ||
        //   this.validatenull(this.gender) ||
        //   this.attributeList.some(
        //     (el) => this.validatenull(el.bindValue) === true
        //   );
        // if (flag) {
        //   this.$message.warning('请选择跳转详情的关联筛选条件');
        //   loading();
        //   return false;
        // }
        const targetObj = { varietyCode: this.breed, gender: this.gender };
        this.attributeList.forEach((v) => {
          targetObj[v.attributeCode] = v.bindValue;
        });
        params.keywordsJson = JSON.stringify(targetObj);
        params.jumpDetail = '';
      } else {
        params.keywordsJson = '';
      }
      params.startDate = row.durationForm[0];
      params.endDate = row.durationForm[1];
      return params;
    },
    // 编辑
    async handleUpdate(row, index, done, loading) {
      try {
        await putObj(this.getParams(row, loading));
        done();
        this.getList();
      } catch (error) {
        loading();
        throw new Error(error);
      }
    },
    // 保存
    async handleSave(row, done, loading) {
      try {
        await addObj(this.getParams(row, loading));
        done();
        this.$message.success('操作成功');
        this.getList(this.page, true);
      } catch (error) {
        loading();
        throw new Error(error);
      }
    },
    // 列表查询
    getList(page, refresh) {
      if (refresh) {
        this.page.current = 1;
        this.page.currentPage = 1;
      }
      this.tableLoading = true;
      const timeObj = {};
      if (this.searchForm.duration && this.searchForm.duration.length) {
        timeObj.startDate = this.searchForm.duration[0];
        timeObj.endDate = this.searchForm.duration[1];
        // delete this.searchForm.duration;
      }
      fetchList(
        Object.assign(
          {
            current: this.page.currentPage,
            size: this.page.pageSize,
          },
          this.searchForm,
          timeObj
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
          this.tableData.forEach((item) => {
            item.duration = `${item.startDate}到${item.endDate}`;
          });
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 打开窗口前的拦截，调用详情接口回显数据
    async beforeOpen(done, type) {
      this.resetData();
      // 如果不是新增
      if (type !== 'add') {
        const { data } = await getObj(this.form.id);
        this.form = data.data;
        this.form.durationForm = [this.form.startDate, this.form.endDate];
        this.form.duration = `${this.form.startDate}到${this.form.endDate}`;
        if (this.form.jumpType === SEARCH_TYPE.PET_RESULT) {
          const keywordsJson = JSON.parse(this.form.keywordsJson);
          this.breed = keywordsJson.varietyCode;
          this.gender = keywordsJson.gender;
          this.attributeList.forEach((el) => {
            el.bindValue = keywordsJson[el.attributeCode];
          });
        }
      }
      done();
    },
    //  导出excel
    exportExcel() {
      this.downBlobFile('/app/appuser/export', this.searchForm, 'appuser.xlsx');
    },
  },
};
</script>
<style lang="scss" scoped>
.title {
  min-width: 60px;
}
.mb-20 {
  margin-bottom: 20px;
}
</style>
